package com.ityls.springsecuritystudy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class KickOutUser {
    @Autowired
    private SessionRegistry sessionRegistry;

    // 踢出指定用户
    @GetMapping("/kickOut")
    public void kickOutUser(String username) {
        // 1.获取全部登录用户
        List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
        // 2.遍历全部登录用户，找到要强制登出的用户
        for (Object principal : allPrincipals) {
            UserDetails userDetail = (UserDetails) principal;
            if (username.equals(userDetail.getUsername())) {
                // 3.找到认证用户所有的会话，不包含过期会话
                List<SessionInformation> sessions = sessionRegistry.getAllSessions(userDetail, false);
                if (null != sessions && !sessions.isEmpty()) {
                    // 4.遍历该用户的会话,使其立即失效
                    for (SessionInformation session : sessions) {
                        session.expireNow();
                    }
                }
            }
        }
    }
}
